package ads.pin.pinmon.dal;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import ads.pin.pinmon.entity.Creature;
import ads.pin.pinmon.entity.Skill;

public class CreatureSkillDAO {
	private EntityManager em = new EntityManager() {

		@Override
		public Object treatResultSet(ResultSet resultSet) throws SQLException {
			Creature creature = new Creature(100, 100, 120, 120);

			creature.setSkills(getAllCreatureSkills(creature.getId()));
			return creature;
		}
	};

	/**
	 * Retorna todas as skills pertencentes a criatura de ID = ?.
	 * 
	 * @param id
	 *            Identificador da criatura.
	 * @return Skills que pertencem a criatura.
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	public List<Skill> getAllCreatureSkills(Integer id) throws SQLException {
		String sql = " select distinct skill_id from creature_skill where creature_id = ?";

		return (List<Skill>) em.getResultList(sql, id);
	}

	/**
	 * Salva na tabela de juncao a criatura e suas skills.
	 * 
	 * @param creature
	 *            Criatura a ser salva.
	 * @throws SQLException
	 */
	public void saveCreatureSkill(Creature creature) throws SQLException {
		String sql = " insert into creature_skill (creature_id, skill_id) "
				+ " values (?, ?) ";

		// Executa a query salvando o id da criatura e o id de cada skill.
		for (Skill skill : creature.getSkills()) {
			em.executeQuery(sql, creature.getId(), skill.getId());

		}
	}
}
